import React, { useEffect, useState } from 'react'
import UserForm from '../../../components/user-manage/UserForm'
import { Button, Table, Tag, Popconfirm, message, Switch, Form, Input, Modal, Radio, Select } from 'antd'
import axios from 'axios'
import {
  DeleteOutlined,
  EditOutlined
} from '@ant-design/icons'
const { Option } = Select;


export default function UserList() {
  const [dataSource, setdataSource] = useState([])
  const [open, setOpen] = useState(false);
  const [openUpdate, setopenUpdate] = useState(false);
  const [roleList, setRoleList] = useState([])
  const [regionList, setRegionList] = useState([])
  const [form] = Form.useForm();
  const [formUpdate] = Form.useForm();
  const [isDisabled, setisDisabled] = useState(false)
  const [current, setcurrent] = useState(null)

  const onCreate = (values) => {
    setOpen(false);
    // todo 
    // values:表单数据
    // post添加
    // 更新datasource
    axios.post("/users?_expand=role", {
      ...values,
      "roleState": true,
      "default": false,
    }).then(res => {
      setdataSource(
        [...dataSource,
        {
          ...res.data,
          role: roleList.filter(item => item.id === values.roleId)[0]
        }])
    })

  };

  const onUpdate = (values) => {
    // values:表单数据
    // post添加
    // 更新datasource
    axios.patch(`/users/${current.id}`, values).then(res => {
      setdataSource(
        dataSource.map(item => {
          if (item.id === current.id) {
            return {
              ...item,
              ...values,
              role: roleList.filter(data => data.id === values.roleId)[0]
            }
          } else {
            return item
          }
        })
      )
      setopenUpdate(false);
    })

  };


  const onCancel = (values) => {
    // console.log('Received values of form: ', values);
    setOpen(false);
  };
  const onCancelUpdate = (values) => {
    // console.log('Received values of form: ', values);
    setopenUpdate(false);
  };
  const handelUpdate = (item) => {
    // console.log('Received item of form: ', item);
    setopenUpdate(true);
    formUpdate.setFieldsValue(item)//把之前的设置上
    setisDisabled(item.region === "" ? true : false)
    setcurrent(item)
  };
  useEffect(() => {
    axios.get("/users?_expand=role").then(res => {
      setdataSource(res.data)
    })
  }, [])
  useEffect(() => {
    axios.get("/roles").then(res => {
      setRoleList(res.data)
    })
  }, [])
  useEffect(() => {
    axios.get("/regions").then(res => {
      setRegionList(res.data)
    })
  }, [])

  const switchChange = (item) => {
    item.roleState = !item.roleState
    setdataSource([...dataSource])

    axios.patch(`/users/${item.id}`, { roleState: item.roleState })
  }

  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      render: (region) => {
        return <b>{region ? region : "全球"}</b>
      },
      filters: [//过滤项
        {
          text: "全球",
          value: "全球"
        },
        ...regionList.map(item => ({
          text: item.title,
          value: item.value
        }))
      ],
      onFilter: (value, item) => {
        if (value === "全球") {
          return item.region === ""
        } else {
          return item.region === value
        }
      },
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (role) => {
        // return role.roleName
        return role != undefined ? role.roleName : ""
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
      render: (key) => {
        return <Tag color="orange">{key}</Tag >
      }

    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return <Switch checked={roleState} disabled={item.default} onChange={() => {
          switchChange(item)
        }} ></Switch >
      }

    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Popconfirm
            title="Delete the task"
            description="Are you sure to delete this task?"
            onConfirm={() => {
              confirm(item)
            }}
            onCancel={cancel}
            okText="Yes"
            cancelText="No"
          >
            <Button danger shape="circle" icon={<DeleteOutlined />} disabled={item.default}></Button>
          </Popconfirm>

          <Button type="primary" shape="circle" icon={<EditOutlined />} disabled={item.default} onClick={() => { handelUpdate(item) }} />
        </div>
      }

    },
  ];

  const delMethod = (item) => {
    setdataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/users/${item.id}`)
  }
  const confirm = (item) => {
    message.success('Click on Yes');
    delMethod(item)
  };
  const cancel = (e) => {
    // console.log(e);
    // message.error('Click on No');
  };

  return (
    <div>
      <Button type="primary" onClick={() => { setOpen(true) }}>添加用户</Button>
      <Table dataSource={dataSource} columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={(item) => item.id}
      />

      <Modal
        open={open}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={onCancel}
        onOk={() => {
          form
            .validateFields()
            .then((values) => {
              form.resetFields();
              onCreate(values);
            })
            .catch((info) => {
              // console.log('Validate Failed:', info);
            });
        }}
      >
        <UserForm regionList={regionList} roleList={roleList} form={form} setisDisabled={setisDisabled} isDisabled={isDisabled}></UserForm>
      </Modal>

      <Modal
        open={openUpdate}
        title="更新用户"
        okText="确定"
        cancelText="取消"
        onCancel={onCancelUpdate}
        onOk={() => {
          formUpdate
            .validateFields()
            .then((values) => {
              // formUpdate.resetFields();
              onUpdate(values);
            })
            .catch((info) => {
              // console.log('Validate Failed:', info);
            });
        }}
      >
        <UserForm regionList={regionList} roleList={roleList} form={formUpdate} setisDisabled={setisDisabled} isDisabled={isDisabled}></UserForm>
      </Modal>

    </div>
  )
}
